/**
 * JAVACC DEMO 1.0
 */
package com.apache.uct.controller;

import com.apache.api.manager.BaseManager;
import com.apache.api.manager.ProxyManager;
import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultMsg;
import com.apache.api.vo.Token;
import com.apache.database.constant.SystemTools;
import com.apache.database.constant.Validator;
import com.apache.tools.DateUtils;
import com.apache.tools.StrUtil;
import com.apache.uct.common.BaseAction;
import com.apache.uct.common.entity.Act;
import com.apache.uct.common.entity.ActGive;
import com.apache.uct.common.entity.Org;
import com.apache.uct.common.entity.User;
import com.apache.uct.manager.ActGiveManager;
import com.apache.uct.manager.ActManager;
import com.apache.uct.manager.OrgManager;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * description:  机构管理action
 *
 * @author iussoft 创建时间：2016-3-11
 */
@Controller
@RequestMapping("uct/org/")
public class OrgAction extends BaseAction<Org> {

    @Autowired
    private OrgManager orgManager;

    @Autowired
    private ProxyManager uctProxyManager;

    @Autowired
    private ActManager actManager;

    @Autowired
    private ActGiveManager actGiveManager;

    //机构树形列表
    @RequestMapping("org!data.action")
    @ResponseBody
    protected Object data(HttpServletRequest request, String page, String rows) {
        String parentId = request.getParameter("id");
        Org org = new Org();
        if (Validator.isNull(parentId)) {
            parentId = "0";
        }
        org.setFatherId(parentId);
        ParamsVo<Org> vo = new ParamsVo<Org>();
        vo.setObj(org);
        User user = this.getSessionUser(request);
        if (!Validator.isEmpty(user) && "1"
                .equals(SystemTools.getInstance().getValue("org_act_switch"))) {
            vo.setParams("userOrgId", user.getOrgId());
            vo.setParams("sysUser", getSysFlag(request));//是否为系统用户
        }
        List<Org> list = orgManager.getList(vo);
        net.sf.json.JSONArray jary = new net.sf.json.JSONArray();
        int count = list.size();
        for (int i = 0; i < count; i++) {
            Org orgVo = list.get(i);
            net.sf.json.JSONObject jvo = net.sf.json.JSONObject.fromObject(orgVo);
            if (null != orgVo.getSubCount() && orgVo.getSubCount() > 0) {
                jvo.put("state", "closed");
            } else {
                jvo.put("state", "opened");
            }
            jary.add(jvo);
        }
        return jary;
    }

    /**
     * 功能说明：跳转到新增页面
     */
    @Token(save = true)
    @RequestMapping(value = "add.action", method = RequestMethod.GET)
    protected ModelAndView add(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(EDIT);
        ParamsVo<Org> vo = new ParamsVo<Org>();
        Org org = null;
        if (Validator.isNotNull(request.getParameter("orgId"))) {
            vo.setInfoId(request.getParameter("orgId"));
            org = (Org) getBaseManager().getInfoById(vo);
        } else {
            org = new Org();
            org.setFatherId(request.getParameter("fatherId"));
        }
        view.addObject("item", org);
        return view;
    }

    /**
     * 功能说明：跳转到新增页面
     */
    @Token(save = true)
    @RequestMapping(value = "add", method = RequestMethod.GET)
    protected String add(HttpServletRequest request, Map<String, Object> data) {
        ParamsVo<Org> vo = new ParamsVo<Org>();
        Org org = null;
        if (Validator.isNotNull(request.getParameter("orgId"))) {
            vo.setInfoId(request.getParameter("orgId"));
            org = (Org) getBaseManager().getInfoById(vo);
        } else {
            org = new Org();
            org.setFatherId(request.getParameter("fatherId"));
        }
        data.put("item", org);
        data.put("ctx", request.getContextPath());
        return EDIT;
    }

    /**
     * TODO 保存机构信息.
     */
    @Token(remove = true)
    @RequestMapping(value = "/save.action", method = RequestMethod.POST)
    @ResponseBody
    public ResultMsg save(HttpServletRequest request, HttpServletResponse response,
            @ModelAttribute Org item) {
        ResultMsg rmsg = new ResultMsg("T", "操作成功！");
        ParamsVo<Org> vo = getParamsVo(request);
        if (Validator.isNull(item.getFatherId()))
            item.setFatherId("0");
        long times = DateUtils.toLong(new Date());
        User user = this.getSessionUser(request);
        if (Validator.isNotNull(item.getOrgId())) {//对机构信息修改
            if (!"0".equals(item.getFatherId())) {
                ParamsVo pvo = new ParamsVo();
                pvo.setInfoId(item.getFatherId());
                Org org = (Org) orgManager.getInfoById(pvo);
                item.setFullEname(org.getFullEname() + "/" + item.getOrgEname());
                item.setFullCname(org.getOrgCname() + "/" + item.getOrgCname());
            } else {
                item.setFullEname("/" + item.getOrgEname());
                item.setFullCname("/" + item.getOrgCname());
            }
            item.setUpdateTime(times);
            int updateCount = item.getUpdateCount() == null ? 0 : item.getUpdateCount();
            item.setUpdateCount(updateCount + 1);
            item.setUpdateUser(user.getUserEname());
            vo.setObj(item);
            boolean mark = getBaseManager().editInfo(vo);
            if (!mark) {
                rmsg = getResultMsg(request, "机构信息修改失败！");
            }
        } else {//添加机构信息
            if ("1".equals(SystemTools.getInstance().getValue("org_act_switch"))) {//是否开启授权
                if (!Validator.isEmpty(user)) {
                    if (!"1".equals(getSysFlag(request)) && "0"
                            .equals(item.getFatherId())) {//是否为系统用户
                        rmsg = getResultMsg(request, "您没有此项操作权限！");
                        return rmsg;
                    }
                } else {
                    rmsg = getResultMsg(request, "用户还没有登录！");
                    return rmsg;
                }
            }
            if (!"0".equals(item.getFatherId())) {
                ParamsVo pvo = new ParamsVo();
                pvo.setInfoId(item.getFatherId());
                Org org = (Org) orgManager.getInfoById(pvo);
                item.setFullEname(org.getFullEname() + "/" + item.getOrgEname());
                item.setFullCname(org.getOrgCname() + "/" + item.getOrgCname());
            } else {
                item.setFullEname("/" + item.getOrgEname());
                item.setFullCname("/" + item.getOrgCname());
            }
            item.setCreateUser(user.getUserEname());
            item.setSysEname("uct");
            item.setUpdateCount(0);
            item.setCreateTime(times);
            item.setRegTime(times);
            vo.setObj(item);
            vo.setKey("checkOrgEname");
            String flag = String.valueOf(orgManager.execute(vo));
            if ("true".equals(flag)) {
                String id = getBaseManager().saveInfo(vo);
                if (Validator.isNull(id)) {
                    rmsg = getResultMsg(request, "机构信息添加失败！");
                }
            } else {
                rmsg = getResultMsg(request, "机构标识[" + item.getOrgEname() + "]已经被使用");
            }
        }
        return rmsg;
    }

    //删除机构信息
    @RequestMapping("del.action")
    @ResponseBody
    public ResultMsg delete(HttpServletRequest request, String id) {
        ResultMsg rmsg = new ResultMsg("T", "删除成功！");
        ParamsVo<Org> vo = getParamsVo(request);
        if (isNotNull(id)) {
            vo.setInfoId(id);
            vo.setKey("deleteOrg");
            vo.setParams("infoType", "org");
            String msg = String.valueOf(uctProxyManager.doInvoke(vo));
            if (Validator.isNotNull(msg)) {
                rmsg.setFlag("F");
                rmsg.setMsg(msg);
            }
        } else {
            rmsg.setFlag("H");
            rmsg.setMsg("请选择要删除的机构！");
        }
        return rmsg;
    }

    //检查是否设置授权权限
    @RequestMapping("org-act!checkAct.action")
    @ResponseBody
    public ResultMsg checkAct(HttpServletRequest request) {
        ResultMsg rmsg = new ResultMsg("T", "成功！");
        if (!"1".equals(SystemTools.getInstance().getValue("org_act_switch"))) {//是否开启授权
            rmsg = new ResultMsg("F", "对不起,您没有此功能的操作权限!");
        }
        return rmsg;
    }

    //跳转到机构授权页面
    @RequestMapping("org-act.action")
    public ModelAndView list(HttpServletRequest request, String orgId) {
        ModelAndView view = new ModelAndView(getPrefix() + "act");
        view.addObject("orgId", orgId);
        return view;
    }

    /**
     * 获取权限分配列表
     */
    @RequestMapping("org-act!data.action")
    @ResponseBody
    public Object dataActs(HttpServletRequest request, String orgId, String id) throws Exception {
        id = Validator.getDefaultStr(id, "0");
        Act actVo = new Act();
        actVo.setFatherId(id);
        ParamsVo<Act> vo = new ParamsVo<Act>();
        vo.setObj(actVo);
        User user = this.getSessionUser(request);
        if (!Validator.isEmpty(user)) {
            vo.setParams("userOrgId", user.getOrgId());
            vo.setParams("sysUser", getSysFlag(request));//是否为系统用户
        }
        List<Act> actList = actManager.getList(vo);
        ParamsVo<ActGive> agVo = new ParamsVo<ActGive>();
        agVo.setParams("roleId", orgId);
        agVo.setParams("giveType", "org");
        agVo.setKey("GiveListByOrgId");
        List<ActGive> giveList = (List<ActGive>) actGiveManager.execute(agVo);

        JSONArray jary = new JSONArray();
        for (int i = 0; i < actList.size(); i++) {
            Act act = actList.get(i);
            JSONObject jvo = JSONObject.fromObject(act);
            if (act.getSubCount() != null && act.getSubCount() > 0) {
                jvo.put("state", "closed");
            } else {
                jvo.put("state", "opened");
            }
            String hasGive = hasGive(giveList, act.getActId()) ? "T" : "F";
            jvo.put("hasGive", hasGive);
            jary.add(jvo);
        }
        return jary;
    }

    //跳转到机构用户列表页面
    @RequestMapping("org-user-list.action")
    public ModelAndView userList(HttpServletRequest request, String orgId) {
        ModelAndView view = new ModelAndView(getPrefix() + "user-list");
        ParamsVo<Org> vo = new ParamsVo<Org>();
        vo.setInfoId(orgId);
        Org org = (Org) orgManager.getInfoById(vo);
        view.addObject("org", org);
        return view;
    }

    //跳转到机构用户列表页面
    @RequestMapping("org-user-list")
    public String userList(HttpServletRequest request, String orgId, Map<String, Object> data) {
        ParamsVo<Org> vo = new ParamsVo<Org>();
        vo.setInfoId(orgId);
        Org org = (Org) orgManager.getInfoById(vo);
        data.put("org", org);
        data.put("ctx", request.getContextPath());
        return getPrefix() + "user-list";
    }

    /**
     * 添加用户界面   初始化机构的下拉列表
     */
    @RequestMapping("org!initOrg.action")
    @ResponseBody
    public Object initOrg(HttpServletRequest request, String orgId) {
        List<Org> orgList = new ArrayList<Org>();
        ParamsVo<Org> vo = new ParamsVo<Org>();
        if (StrUtil.isNull(orgId)) {
            orgList = orgManager.getList(vo);
        } else {
            vo.setInfoId(orgId);
            Org org = (Org) orgManager.getInfoById(vo);
            orgList.add(org);
            User user = this.getSessionUser(request);
            if (!Validator.isEmpty(user)) {
                vo.setParams("userOrgId", user.getOrgId());
                vo.setParams("sysUser", getSysFlag(request));//是否为系统用户
            }
            Org orgvo = new Org();
            orgvo.setFatherId(orgId);
            vo.setObj(orgvo);
            List<Org> list = orgManager.getList(vo);
            if (null != list && list.size() > 0)
                orgList.addAll(list);
        }

        net.sf.json.JSONObject jvo = new net.sf.json.JSONObject();
        net.sf.json.JSONArray jary = new net.sf.json.JSONArray();
        if (Validator.isEmpty(orgList))
            return jary;
        for (int i = 0; i < orgList.size(); i++) {
            Org ovo = orgList.get(i);
            jvo.put("orgId", ovo.getOrgId());
            jvo.put("orgCname", ovo.getOrgCname());
            jary.add(jvo);
        }
        return jary;
    }

    protected BaseManager<Org> getBaseManager() {
        return orgManager;
    }

    protected String getPrefix() {
        return "uct/org-";
    }

    /**
     * 判断是否包含该权限值
     *
     * @param giveList 分配的权限值
     * @param actId 权限值id
     * @return boolean
     */
    private boolean hasGive(List<ActGive> giveList, String actId) {
        if (Validator.isEmpty(giveList))
            return false;
        for (int j = 0; j < giveList.size(); j++) {
            ActGive give = giveList.get(j);
            if (actId.equals(give.getActId())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 通过主键获取实体
     */
    @RequestMapping("getById.action")
    @ResponseBody
    public Object getById(HttpServletRequest request, String id) {
        ParamsVo<Org> vo = new ParamsVo<Org>();
        Org org = null;
        if (Validator.isNotNull(id)) {
            vo.setInfoId(id);
            org = (Org) getBaseManager().getInfoById(vo);
        }
        return org;
    }
}
